<template>
  <div>
    <div>
      <h2>传统医药</h2>
      <div>
        <div v-for="(category, index) in categoryMedicineList" :key="index">
          <el-link type="primary" style="margin: 1%;float: left" @click="navigateToCategory(category)">【{{ category }}】</el-link>
        </div>
      </div>
    </div>
    <div style="margin-top: 10%;white-space: nowrap">
      <h2>西药</h2>
      <div>
        <div v-for="(category, index) in categoryWestormMedicineList" :key="index">
          <el-link type="primary" style="margin: 1%;float: left" @click="navigateToCategoryWestormMedicine(category)">【{{ category }}】</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { tcCategory, vMCategory } from '@/api/category'

export default {
  data () {
    return {
      categoryMedicineList: [],
      categoryWestormMedicineList: []
    }
  },
  mounted () {
    this.categoryMedicine()
    this.categoryWestormMedicine()
  },
  methods: {
    // 获取分类
    categoryMedicine () {
      tcCategory().then(resp => {
        this.categoryMedicineList = resp.data.map(item => item.category)
        // alert(this.categoryMedicineList)
      }).catch(err => {
        this.handleAxiosError(err)
      })
    },
    async categoryWestormMedicine () {
      await vMCategory().then(resp => {
        this.categoryWestormMedicineList = resp.data.map(item => item.category)
        // alert(this.categoryMedicineList)
      }).catch(err => {
        this.handleAxiosError(err)
      })
    },
    navigateToCategory (category) {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      this.$router.push({ name: 'cagetoryMedicine', params: { category } })
    },
    navigateToCategoryWestormMedicine (category) {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      this.$router.push({ name: 'westernCagetoryMedicine', params: { category: category } })
    },
    handleAxiosError (err) {
      if (err.isAxiosError && err.response) {
        this.$message.error('网络请求失败，请稍后重试')
      } else {
        // 处理其他类型的错误
        this.$message.error('网络请求失败，发生错误，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>

</style>
